package com.jinghao.tws.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jinghao.core.common.exception.JingHaoCustomerException;
import com.jinghao.core.common.service.impl.JingHaoBaseServiceImpl;
import com.jinghao.core.common.util.JhHttpClientUtil;
import com.jinghao.core.common.util.cnd.JhCnd;
import com.jinghao.core.common.util.cnd.JhUpdate;
import com.jinghao.tws.entity.WvAccessConfig;
import com.jinghao.tws.entity.WvCloudAccessConfig;
import com.jinghao.tws.entity.WvPallet;
import com.jinghao.tws.entity.WvPallet.EWvPallet;
import com.jinghao.tws.entity.WvProcess;
import com.jinghao.tws.entity.WvProcess.EWvProcess;
import com.jinghao.tws.entity.WvProduct.EWvProduct;
import com.jinghao.tws.entity.WvTaskInfo;
import com.jinghao.tws.entity.WvTaskInfo.EWvTaskInfo;
import com.jinghao.tws.entity.WvUploadTaskInfo;
import com.jinghao.tws.entity.WvUploadTaskInfo.EWvUploadTaskInfo;
import com.jinghao.tws.service.IWvAccessConfigService;
import com.jinghao.tws.service.IWvPalletService;
import com.jinghao.tws.service.IWvProcessMergeConfigService;
import com.jinghao.tws.service.IWvProcessService;
import com.jinghao.tws.service.IWvPublicSynchronousService;
import com.jinghao.tws.service.IWvTaskInfoService;
import com.jinghao.tws.service.IWvUploadTaskInfoService;
import com.jinghao.tws.util.EJhTwsCode;

@Service("wvProcessService")
public class WvProcessServiceImpl extends JingHaoBaseServiceImpl<WvProcess> implements IWvProcessService {
	//==================定制内容开始======================
//在这里修改代码
	@Resource
	private IWvUploadTaskInfoService wvUploadTaskInfoService;
	
	@Resource
	private IWvTaskInfoService wvTaskInfoService;
	
	@Resource
	private IWvAccessConfigService wvAccessConfigService;
	
	@Resource
	private IWvPalletService wvPalletService;
	
	@Resource
	private IWvProcessMergeConfigService wvProcessMergeConfigService;
	
	@Resource
	private IWvProcessService wvProcessService;
	
	@Resource
	private IWvPublicSynchronousService wvPublicSynchronousService;
	
	
	@Override
	public void updateWvProcessUrlLink(WvProcess model) {
		Map<String,Object> map=model.getObjMap();
		if(map==null){
			throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请求参数有误 ！");
		}
		if(map.get("processUuid")==null||StringUtils.isEmpty(map.get("processUuid").toString())){
			throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供产品UUID名称！");
		}
		model.setProcessUuid(map.get("processUuid").toString());
		
		if(map.get("urlLink")==null||StringUtils.isEmpty(map.get("urlLink").toString())){
			throw new JingHaoCustomerException(EJhTwsCode.TWS4001.getCode(),"请提供视频地址信息名称！");
		}
		model.setUrlLink(map.get("urlLink").toString());
	 
		JhCnd cnd = new JhCnd();
		cnd.andEquals("processUuid");
		model.lnkCnd(cnd);
		JhUpdate update=new JhUpdate();
		update.add("urlLink").add("urlStatus").add("fileUploadStatus");
		model.setUrlStatus(EWvProcess.urlStatus_1.getKey());
		model.setFileUploadStatus(EWvPallet.fileUploadStatus_2.getKey());
		model.setJhUpdate(update);
		this.updateSame(model);
		
		
		//保存视频任务生成
		WvUploadTaskInfo wvTaskInfo=new WvUploadTaskInfo();
		wvTaskInfo.setTaskUuid(model.getUUID());
		wvTaskInfo.setCreateTime(new Date());
		wvTaskInfo.setTaskType(EWvUploadTaskInfo.taskType_6.getKey());
		wvTaskInfo.setWorkUuid(model.getProcessUuid());
		wvTaskInfo.setTaskLevel(EWvUploadTaskInfo.taskType_6.getKey());
		this.wvUploadTaskInfoService.add(wvTaskInfo);
		
	}
	
	public void updateStopGenerateVideo(WvProcess model){
		if(StringUtils.isEmpty(model.getProcessUuid())){
			throw new JingHaoCustomerException("提供环节UUID信息！");
		}
		WvTaskInfo wvTask =new WvTaskInfo();
		JhCnd cnd=new JhCnd();
		cnd.reset();
		cnd.andEquals("fprocessUuid");
		wvTask.setFprocessUuid(model.getProcessUuid());
		cnd.andEquals("type");
		wvTask.setType(EWvTaskInfo.type_1.getKey());
		wvTask.setJhCnd(cnd);
		this.wvTaskInfoService.deleteSame(wvTask);
		
		Map<String,Object> dataMap=new HashMap<String,Object>();
		dataMap.put("urlStatus", EWvProduct.urlStatus_0.getKey());
		List<Map<String,Object>> datalist=new ArrayList<Map<String,Object>>();
		datalist.add(dataMap);
		model.setMapList(datalist);
	}
	@Override
	public void updateGenerateVedio(WvProcess model) {
		if(StringUtils.isEmpty(model.getProcessUuid())){
			throw new JingHaoCustomerException("提供环节UUID信息！");
		}
		WvProcess wvProcess=this.get(model);
		if(wvProcess==null){
			throw new JingHaoCustomerException("未找到环节信息！");
		}
		JhCnd cnd=new JhCnd();
		WvPallet wvPallet=new WvPallet();
		wvPallet.setPalletId(wvProcess.getFpalletId());
		cnd.andEquals("palletId");
		wvPallet.setJhCnd(cnd);
		List<WvPallet> list=this.wvPalletService.queryModelList(wvPallet);
		if(list==null||list.size()<=0){
			throw new JingHaoCustomerException("未找到环节信息！");
		}
		wvPallet=list.get(0);
		//删除云服务器信息
		this.synchronousReSetProcess(wvProcess);
		String medioInfo=this.getVedioMediaInfo(wvProcess,wvPallet);
		if(medioInfo!=null&&!medioInfo.trim().equals("")){
			Map<String,Object> map=new HashMap<String,Object>();
			this.updateGenerateVideoTask(wvProcess,medioInfo,wvPallet,map);
			List<Map<String,Object>> datalist=new ArrayList<Map<String,Object>>();
			datalist.add(map);
			model.setMapList(datalist);
		}else{
			throw new JingHaoCustomerException("未找到对应合并环节信息！");
		}
	}
	public void updateGenerateVedioTemp(WvProcess model) {
		if(StringUtils.isEmpty(model.getProcessUuid())){
			throw new JingHaoCustomerException("提供环节UUID信息！");
		}
		WvProcess wvProcess=this.get(model);
		if(wvProcess==null){
			throw new JingHaoCustomerException("未找到环节信息！");
		}
		JhCnd cnd=new JhCnd();
		WvPallet wvPallet=new WvPallet();
		wvPallet.setPalletId(wvProcess.getFpalletId());
		cnd.andEquals("palletId");
		wvPallet.setJhCnd(cnd);
		List<WvPallet> list=this.wvPalletService.queryModelList(wvPallet);
		if(list==null||list.size()<=0){
			throw new JingHaoCustomerException("未找到环节信息！");
		}
		wvPallet=list.get(0);
		//删除云服务器信息
		//this.synchronousReSetProcess(wvProcess);
		String medioInfo=this.getVedioMediaInfo(wvProcess,wvPallet);
		if(medioInfo!=null&&!medioInfo.trim().equals("")){
			WvTaskInfo wvTask=new WvTaskInfo();
			wvTask.setTaskUuid(model.getUUID());
			wvTask.setFprocessUuid(wvProcess.getProcessUuid());
			wvTask.setFpalletUuid(wvPallet.getPalletUuid());
			wvTask.setFprocessId(wvProcess.getFprocessId());
			wvTask.setFpalletId(wvPallet.getPalletId());
			wvTask.setCreateTime(new Date());
			wvTask.setMedioInfo(medioInfo);
			wvTask.setVideoStatus(EWvTaskInfo.videoStatus_1.getKey());
			wvTask.setLastCheckTime(new Date());
			wvTask.setType(EWvTaskInfo.type_1.getKey());
			//wvTask.setRequestId();
			this.wvTaskInfoService.add(wvTask);
		}else{
			throw new JingHaoCustomerException("未找到对应合并环节信息！");
		}
	}
	
	@Override
	public void updateReSetAllGenerateVedio(WvProcess model) {
		 JhCnd cnd =new JhCnd();
		 cnd.andEquals("fprocessId");
		 model.setFprocessId("tallying");
		 model.setJhCnd(cnd);
		 model.setPage(null);
		 List<WvProcess> list=this.queryModelList(model);
		 for(WvProcess newModel:list){
			 this.updateGenerateVedioTemp(newModel);
		 }
		 if(list!=null){
			 list.clear();
			 list=null;
		 }
	}

	public void synchronousReSetProcess(WvProcess wvProcess){
		WvCloudAccessConfig model=new WvCloudAccessConfig();
		//第一步：查询是否配置云段接口及云平台验证
		Map<String,Object> dateInfo=this.wvPublicSynchronousService.cloudLogin(model);
		model=(WvCloudAccessConfig)dateInfo.get("wvCloudAccessConfig");
		JhHttpClientUtil hd = new JhHttpClientUtil();
		Map<String,String> map=new HashMap<String,String>();
		Object obj=dateInfo.get("loginInfo");
		Map<String,Object> loginInfo=(Map<String,Object>)obj;
		map.put("accessTokenData", JSON.toJSONString(loginInfo));
		Map<String,Object> dataMap=null;
		if(wvProcess!=null){
			dataMap=new HashMap<String,Object>();
			dataMap.put("processUuid", wvProcess.getProcessUuid());
			dataMap.put("fileName", wvProcess.getFpalletId()+wvProcess.getFprocessId());
			map.put("jhPublicData", JSON.toJSONString(dataMap));
			String dtUrl="app/ctws/public/syn/updateReSetProcessFile";
			String httpUrl=model.getAddress();
			if(httpUrl.substring(httpUrl.length()-1, httpUrl.length()).equals("/")){
				httpUrl=model.getAddress()+""+dtUrl;
			}else{
				httpUrl=model.getAddress()+"/"+dtUrl; 
			}
			String msg= hd.post(httpUrl, map);
			this.wvPublicSynchronousService.checkResult(msg);
		} 
	}
	public void updateGenerateVideoTask(WvProcess model,String medioInfo,WvPallet wvPallet,Map<String,Object> dataMap){
		WvAccessConfig wvAccessConfig=this.wvAccessConfigService.getWvAccessConfigInfo();
		String userName=wvAccessConfig.getUsername();
		String password=wvAccessConfig.getPassword();
		String dtUrl=wvAccessConfig.getBucket();
		String httpUrl=wvAccessConfig.getAddress();
		if(httpUrl.substring(httpUrl.length()-1, httpUrl.length()).equals("/")){
			httpUrl=wvAccessConfig.getAddress()+""+dtUrl;
		}else{
			httpUrl=wvAccessConfig.getAddress()+"/"+dtUrl;
		}
		int isSuccess=0;
		String url="";
		WvTaskInfo wvTask=new WvTaskInfo();
		//第一步：登录 
		String sessionKey=this.wvAccessConfigService.vmsLogin(userName,password,httpUrl);
		String  concatenateRequestId=null;
		Map<String,Object> videoMap=this.wvAccessConfigService.vmsRequestconcatenatevideo(httpUrl,sessionKey,medioInfo);
		if(videoMap.get("result")!=null&&videoMap.get("result").toString().equals("ok")){
			concatenateRequestId=videoMap.get("concatenate-request-id").toString();
        }else{
        	concatenateRequestId=null;
        }
		Map<String,Object> resultMap=null,fileMap=null;
		if(concatenateRequestId!=null&&!concatenateRequestId.trim().equals("")){
			//第三步：获取视频生成状态
			resultMap=this.wvAccessConfigService.vmsCheckconcatenatevideostatus(httpUrl,sessionKey, concatenateRequestId);
			if(resultMap!=null&&resultMap.get("result")!=null&&resultMap.get("result").toString().equals("ok")){
				if(resultMap.get("status")!=null&&resultMap.get("status").toString().equals("COMPLETED")){
					if(resultMap.get("file")!=null){
						fileMap=(Map<String,Object>)resultMap.get("file");
						if(fileMap.get("url")!=null){
							isSuccess=2;
							url=fileMap.get("url").toString();
						}else{
							wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
							wvTask.setErrorInfo(JSON.toJSONString(resultMap));
							//未知错误信息
							this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
						}
					}else{
						wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
						wvTask.setErrorInfo(JSON.toJSONString(resultMap));
						//未知错误信息
						this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
					}
					
				}else if(resultMap.get("status")!=null&&resultMap.get("status").toString().equals("IN_PROGRESS")){
					if(resultMap.get("progress")!=null){
						isSuccess=1;
						wvTask.setProgress(Integer.parseInt(resultMap.get("progress").toString()));
						wvTask.setVideoStatus(EWvTaskInfo.videoStatus_2.getKey());
					}else{
						wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
						wvTask.setErrorInfo(JSON.toJSONString(resultMap));
						//未知错误信息
						this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
					}
				}else{
					wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
					wvTask.setErrorInfo(JSON.toJSONString(resultMap));
					//未知错误信息
					this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
				}
			}else if(resultMap!=null&&resultMap.get("result")!=null&&resultMap.get("result").toString().equals("error")){
				wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
				wvTask.setErrorInfo(JSON.toJSONString(resultMap));
			}else{
				wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
				wvTask.setErrorInfo(JSON.toJSONString(resultMap));
				//未知错误信息
				this.logger.info("自动生成视频异常信息（checkconcatenatevideostatus）：时间："+new Date()+",result:"+JSON.toJSONString(resultMap));
			}
		}else{
			wvTask.setVideoStatus(EWvTaskInfo.videoStatus_9.getKey());
			wvTask.setErrorInfo(JSON.toJSONString(videoMap));
        	this.logger.info("自动生成视频异常信息（vmsRequestconcatenatevideo）：时间："+new Date()+",mediaInfo:"+medioInfo+",result:"+JSON.toJSONString(videoMap));
		}
		WvProcess wvProcess=null;
		JhUpdate updateSet=new JhUpdate();
		JhCnd cnd=new JhCnd();
		//第四步：更新任务信息表
		if(isSuccess==0){//生成失败
			throw new JingHaoCustomerException("生成视频发生错误！错误信息："+wvTask.getErrorInfo());
			//throw new JingHaoCustomerException("生成视频发生错误！");
			//dataMap.put("urlStatus", EWvProcess.urlStatus_0.getKey());
			//dataMap.put("videoStatus", EWvTaskInfo.videoStatus_9.getKey());
			//dataMap.put("errorInfo", wvTask.getErrorInfo());
			
		}else if(isSuccess==1){ //生成中
			
			//环节视频
			cnd.reset();
			wvProcess=new WvProcess();
			wvProcess.setProcessUuid(model.getProcessUuid()); 
			wvProcess.setUrlStatus(EWvProcess.urlStatus_0.getKey());
			wvProcess.setFileUploadStatus(EWvPallet.fileUploadStatus_0.getKey());
			cnd.andEquals("processUuid");
			wvProcess.setJhCnd(cnd);
			updateSet.add("urlStatus").add("fileUploadStatus");
			wvProcess.setUpdateSet(updateSet);
			this.wvProcessService.updateSame(wvProcess);
			
			
			cnd.reset();
			cnd.andEquals("fprocessUuid");
			wvTask.setFprocessUuid(model.getProcessUuid());
			cnd.andEquals("type");
			wvTask.setType(EWvTaskInfo.type_1.getKey());
			wvTask.setJhCnd(cnd);
			this.wvTaskInfoService.deleteSame(wvTask);
			
			wvTask.setTaskUuid(model.getUUID());
			wvTask.setFprocessUuid(model.getProcessUuid());
			wvTask.setFpalletUuid(wvPallet.getPalletUuid());
			wvTask.setFprocessId(model.getFprocessId());
			wvTask.setFpalletId(wvPallet.getPalletId());
			wvTask.setCreateTime(new Date());
			wvTask.setMedioInfo(medioInfo);
			wvTask.setVideoStatus(EWvTaskInfo.videoStatus_2.getKey());
			wvTask.setLastCheckTime(new Date());
			wvTask.setType(EWvTaskInfo.type_1.getKey());
			wvTask.setRequestId(concatenateRequestId);
			this.wvTaskInfoService.add(wvTask);
			
			dataMap.put("urlStatus", EWvProcess.urlStatus_0.getKey());
			dataMap.put("videoStatus", EWvTaskInfo.videoStatus_2.getKey());
			dataMap.put("progress", wvTask.getProgress());
			
		}else if(isSuccess==2){//生成成功
			
			//环节视频
			cnd.reset();
			updateSet.add("urlStatus").add("urlLink").add("fileUploadStatus");
			wvProcess=new WvProcess();
			wvProcess.setProcessUuid(model.getProcessUuid()); 
			wvProcess.setUrlLink(url);
			wvProcess.setUrlStatus(EWvProcess.urlStatus_1.getKey());
			wvProcess.setFileUploadStatus(EWvPallet.fileUploadStatus_1.getKey());
			cnd.andEquals("processUuid");
			wvProcess.setJhCnd(cnd);
			wvProcess.setUpdateSet(updateSet);
			this.wvProcessService.updateSame(wvProcess);
			
			cnd.reset();
			cnd.andEquals("fprocessUuid");
			wvTask.setFprocessUuid(model.getProcessUuid());
			cnd.andEquals("type");
			wvTask.setType(EWvTaskInfo.type_1.getKey());
			wvTask.setJhCnd(cnd);
			this.wvTaskInfoService.deleteSame(wvTask);
			
			dataMap.put("urlStatus", EWvProcess.urlStatus_1.getKey());
			dataMap.put("urlLink", wvProcess.getUrlLink());
		}
		 
	}
	
	public String getVedioMediaInfo(WvProcess wvProcess,WvPallet wvPallet){
		JhCnd cnd=new JhCnd();
		cnd.reset();
		cnd.andEquals("processUuid");
		cnd.append(" and pc.fcode='"+wvPallet.getFlowCode()+"'  and pc.process_id<>'tally-event' ");
		wvProcess.lnkCnd(cnd);
		wvProcess.setPage(null);
		List<Map<String,Object>> listProcess=this.queryMapListById(wvProcess,"queryWvProcessAndCamera");
		if(listProcess==null||listProcess.size()<=0){
			throw new JingHaoCustomerException(EJhTwsCode.TWS10002.getCode(),"未找到对应合并环节信息！");
		}
		List<Map<String,Object>> bList=new ArrayList<Map<String,Object>>();
		List<List<Map<String,Object>>> aList=new ArrayList<List<Map<String,Object>>>();
		Date fromDate,toDate;
		Map<String,Object> totalDataMap=null;
		for(Map<String,Object> map:listProcess){
			fromDate=(Date)map.get("startTime");
			toDate=(Date)map.get("endTime");
			totalDataMap=new HashMap<String,Object>();
			totalDataMap.put("deviceId", Integer.parseInt(map.get("deviceId").toString()));
			totalDataMap.put("channelId", Integer.parseInt(map.get("channelId").toString()));
			totalDataMap.put("from", fromDate.getTime());
			totalDataMap.put("to", toDate.getTime());
			bList.add(totalDataMap);
		}
		aList.add(bList);
		return JSON.toJSONString(aList);
	}
	//==================定制内容结束======================
}
